package com.cyj.dream.admin.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.cyj.dream.admin.service.system.LoginService;
import com.cyj.dream.core.constant.Constant;
import com.cyj.dream.core.util.codec.Base64Utils;
import com.cyj.dream.core.util.nosql.RedisUtil;
import com.cyj.dream.core.util.rsa.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.KeyPair;

/**
 * @Description: 登录所用方法的实现类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.dream.DreamChardonnay.service.impl
 * @Author: ChenYongJia
 * @CreateTime: 2021-06-04 12:00
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 前端获取公钥
     *
     * @return java.lang.String
     * @date 2021/6/7 14:40
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public String getPublicKey() {
        try {
            Object privateKey = redisUtil.get(Constant.RSA_PRIVATE_KEY);
            Object publicKey = redisUtil.get(Constant.RSA_PUBLIC_KEY);
            if (ObjectUtil.isEmpty(publicKey) || ObjectUtil.isEmpty(privateKey)) {
                KeyPair keyPair = RSAUtils.getKeyPair();
                privateKey = new String(Base64Utils.encoder(keyPair.getPrivate().getEncoded()));
                publicKey = new String(Base64Utils.encoder(keyPair.getPublic().getEncoded()));
                // 存入私钥
                redisUtil.set(Constant.RSA_PRIVATE_KEY, privateKey);
                // 存入公钥
                redisUtil.set(Constant.RSA_PUBLIC_KEY, publicKey);
            }
            log.info("privateKey = {}，publicKey = {}", privateKey, publicKey);
            return publicKey.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
